#!/usr/bin/env python

"""Draws a sort of random flight but constrained to a small set of angles"""
import android
import random, math, pygame
from pygame.locals import *

#constants, sort of
WINSIZE = [480, 800]
WINCENTER = [240, 400]
#DMAX = 240
# Pareto shape parameter
ALPHA = 1.5


def dist(a,b):
    dy2 = (b[1]-a[1])*(b[1]-a[1])
    dx2 = (b[0]-a[0])*(b[0]-a[0])
    return math.sqrt(dy2+dx2)

def next_point(prev, segments):
    "choose next destination"
    segment = random.randrange(0, segments)
    angle = segment*(2*math.pi)/segments
#    angle = random.normalvariate(0,1.8)
    distance = 2 * random.paretovariate(ALPHA)
#    distance = 2 * random.weibullvariate(1.0, 0.9)
    # cap distance at DMAX
#    if distance > DMAX:
#        distance = DMAX
    point = [(math.sin(angle) * distance)+prev[0], (math.cos(angle) * distance)+prev[1]]
    return point

def main():
    segments = 8
    random.seed()
    clock = pygame.time.Clock()
    #initialize and prepare screen
    pygame.init()
    screen = pygame.display.set_mode(WINSIZE)
    pygame.display.set_caption('Citywalk')
    white = 255, 240, 200
    black = 20, 20, 40
    screen.fill(black)

    done = False
    walks = [
      {"p": WINCENTER[:], "c": white},
      {"p": WINCENTER[:], "c": (240,  20,  20)},
      {"p": WINCENTER[:], "c": (20,  240,  20)},
      {"p": WINCENTER[:], "c": (20,   20, 240)}
    ]
    
    while not done:
        if android is not None and android.check_pause():
            android.wait_for_resume()
        # add point
        q = WINCENTER[:]
        for w in walks:
          p = w["p"]
          q = next_point(w["p"], segments)
          # draw line
          pygame.draw.line(screen, w["c"], p, q, 1)
          w["p"] = q
        pygame.display.update()
        for e in pygame.event.get():
            if e.type == QUIT or (e.type == KEYUP and e.key == K_ESCAPE):
                done = True
                break
            elif e.type == MOUSEBUTTONDOWN and e.button == 1:
                # start a new random walk on click
                if segments == 8:
                  segments = 3
                else:
                  segments += 1
                for w in walks:
                  w["p"] = list(e.pos)
                screen.fill(black)
                break
        # run up to 90 FPS
        clock.tick(90)

# if python says run, then we should run
if __name__ == '__main__':
    main()


